﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LunwenYun.Infrastructure.Entities.Entity;
using LunwenYun.Infrastructure.Entities;
using System.Linq.Expressions;
using LunwenYun.Infrastructure.Entities.Repository;
using LunwenYun.Infrastructure.Entities.Enum;
using LunwenYun.Tool.Framework;
using LunwenYun.Engine.ExServer.WorkPool;
using LunwenYun.Engine.ExServer.WorkPool.WorkHandle.Email;
using LunwenYun.Portal.Biz.Content;
using LunwenYun.Tool.Configration;
using System.Web;

namespace LunwenYun.Portal.Biz
{
    public class SystemBiz
    {
        #region 期刊相关
        /// <summary>
        /// 检查是否有重复的期刊
        /// 可以添加return true;
        ///    否则return false;
        /// </summary>
        /// <param name="periodicalName"></param>
        /// <returns></returns>
        public static bool CheckPeriodicalName(string periodicalName)
        {
            if (String.IsNullOrEmpty(periodicalName.Trim()))
            {
                return false;
            }
            using (Context ctx = new Context())
            {
                return !ctx.Periodical.Any(c => c.Name == periodicalName.Trim());
            }
        }
        /// <summary>
        /// 新增期刊
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static Periodical NewPeriodical(string agentUsername, Periodical model)
        {
            if (model != null && CheckPeriodicalName(model.Name))
            {
                if (!String.IsNullOrEmpty(agentUsername))
                {
                    var user = new User().Find(agentUsername);
                    if (user == null || !(user.SystemRole == UserRole.PaperAgent ||
                        user.SystemRole == UserRole.Admin))
                    {
                        return null;
                    }
                    var periodical = model.PostAdd();
                    if (periodical != null)
                    {
                        if (HttpContext.Current.User.Identity.Name.ToLower().Trim() != "admin@lunwenyun.com")
                        {
                            string support = System.Configuration.ConfigurationManager.AppSettings["support"];
                            if (!String.IsNullOrEmpty(support))
                            {
                                string[] email = support.Split(',');
                                foreach (var u in email)
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                        new NormalNotifyEmail()
                                        {
                                            Message = EmailBuilder.BuildNewPeriodicalNotify(periodical.Name, agentUsername),
                                            Title = SiteResource.SiteName + "-- 有人添加了新期刊，请尽快审核",
                                            Recipient = u
                                        });
                                }
                            }
                        }
                        new Agent()
                        {
                            PeriodicalId = periodical.Id,
                            RecordDate = DateTime.Now,
                            RefreshDate = DateTime.Now,
                            UserName = agentUsername,
                            Rank = 1
                        }.PostAdd();
                        return periodical;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 查询期刊
        /// </summary>
        /// <param name="where"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Periodical> GetAllPeriodical(Expression<Func<T_Periodical,bool>> where, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var query = ctx.Periodical
                    .Where(where)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Periodical().Set(c))
                    .ToList();
                return query;
            }
        }
        public static int GetAllPeriodicalForPage(Expression<Func<T_Periodical, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var query = ctx.Periodical
                    .Count(where);
                return query;
            }
        }
        /// <summary>
        /// 查询期刊
        /// </summary>
        /// <param name="indType"></param>
        /// <param name="subIndType"></param>
        /// <param name="aptitude"></param>
        /// <param name="lang"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Periodical> GetAllPeriodical(int indType, int subIndType, int aptitude, int lang, string journalName, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var query = ctx.Periodical.Where(c=>c.IsActive);
                if (indType != -1)
                {
                    query = query.Where(c => c.IndType == indType);
                }
                if (subIndType != -1)
                {
                    query = query.Where(c => c.SubIndType == subIndType);
                }
                if (aptitude != -1)
                {
                    string aptStr = ";"+ aptitude.ToString()+";";
                    query = query.Where(c => c.Aptitude.Contains(aptStr));
                }
                if (lang != -1)
                {
                    query = query.Where(c => c.Language == lang);
                }
                if (!String.IsNullOrEmpty(journalName))
                {
                    query = query.Where(c => c.Name.Contains(journalName));
                }
                query = query.OrderByDescending(c => c.Id).Skip(page * pageSize).Take(pageSize);
                return query.ToList().Select(c => new Periodical().Set(c)).ToList();
            }
        }
        public static int GetAllPeriodicalForPage(int indType, int subIndType, int aptitude, int lang, string journalName)
        {
            using (Context ctx = new Context())
            {
                var query = ctx.Periodical.Where(c => c.IsActive);
                if (indType != -1)
                {
                    query = query.Where(c => c.IndType == indType);
                }
                if (subIndType != -1)
                {
                    query = query.Where(c => c.SubIndType == subIndType);
                }
                if (aptitude != -1)
                {
                    string aptStr = ";" + aptitude.ToString() + ";";
                    query = query.Where(c => c.Aptitude.Contains(aptStr));
                }
                if (lang != -1)
                {
                    query = query.Where(c => c.Language == lang);
                }
                if (!String.IsNullOrEmpty(journalName))
                {
                    query = query.Where(c => c.Name.Contains(journalName));
                }
                
                return query.Count();
            }
        }
        /// <summary>
        /// 查询所有待审核的新建期刊
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Periodical> GetAllNewPeriodicalApply(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Periodical
                            join u in ctx.User
                             on c.Creator equals u.UserName
                            where !c.IsActive
                            orderby c.Id ascending
                            select new { c, u })
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Periodical().Set(c.c).LoadCreator(new User().Set(c.u)))
                           .ToList();
                return data;
            }
        }
        public static int GetAllNewPeriodicalApplyForPage()
        {
            using (Context ctx = new Context())
            {
                return ctx.Periodical.Count(c => !c.IsActive);
            }
        }
        public static Periodical PutNewPeriodical(int id)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user != null && user.SystemRole == UserRole.Admin)
                {
                    var periodical = new Periodical().Find(id.ToString());
                    if (periodical != null && !periodical.IsActive)
                    {
                        periodical.IsActive = true;
                        periodical.PostModify();
                        return periodical;
                    }
                }
            }
            return null;
        }

        public static Periodical DeleteNewPeriodical(int id)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user != null && user.SystemRole == UserRole.Admin)
                {
                    var periodical = new Periodical().Find(id.ToString());
                    if (periodical != null && !periodical.IsActive)
                    {
                        periodical.PostDelete();
                        return periodical;
                    }
                }
            }
            return null;
        }
        #endregion

        #region 稿件相关
        /// <summary>
        /// 查询所有投稿（意向）
        /// </summary>
        /// <param name="ind"></param>
        /// <param name="p"></param>
        /// <param name="apt"></param>
        /// <param name="lang"></param>
        /// <param name="p_2"></param>
        /// <param name="p_3"></param>
        /// <returns></returns>
        public static List<Article> GetAllManuscript(int ind, int subind, int apt, int lang, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var query = ctx.Article.Where(c=>!c.IsDelete);
                if (ind != -1)
                {
                    query = query.Where(c => c.IndType == ind);
                }
                if (subind != -1)
                {
                    query = query.Where(c => c.SubIndType == subind);
                }
                if (apt != -1)
                {
                    string aptStr = ";" + apt.ToString() + ";";
                    query = query.Where(c => c.Aptitude.Contains(aptStr));
                }
                if (lang != -1)
                {
                    query = query.Where(c => c.Language == lang);
                }
                query = query.OrderByDescending(c => c.Id).Skip(page * pageSize).Take(pageSize);
                return query.ToList().Select(c => new Article().Set(c)).ToList();
            }
        }
        public static int GetAllManuscriptForPage(int ind, int subind, int apt, int lang)
        {
            using (Context ctx = new Context())
            {
                var query = ctx.Article.Where(c => !c.IsDelete);
                if (ind != -1)
                {
                    query = query.Where(c => c.IndType == ind);
                }
                if (subind != -1)
                {
                    query = query.Where(c => c.SubIndType == subind);
                }
                if (apt != -1)
                {
                    string aptStr = ";" + apt.ToString() + ";";
                    query = query.Where(c => c.Aptitude.Contains(aptStr));
                }
                if (lang != -1)
                {
                    query = query.Where(c => c.Language == lang);
                }
                return query.Count();
            }
        }
        /// <summary>
        /// 投稿（发布投稿意向）
        /// </summary>
        /// <param name="article"></param>
        /// <param name="targetJournal"></param>
        /// <returns></returns>
        public static Article SubmitArticle(Article article, string targetJournal)
        {
            if (article != null)
            {
                article = article.PostAdd();
                if (article == null)
                {
                    return null;
                }

                List<string> target = new List<string>();
                if (!String.IsNullOrEmpty(targetJournal))
                {
                   target = targetJournal.Split(';')
                        .Where(c => !String.IsNullOrEmpty(c))
                        .Distinct()
                        .ToList();
                }
                foreach (var item in target)
                {
                    try
                    {
                        new Purpose()
                        {
                            ArticleId = article.Id,
                            CreateTime = DateTime.Now,
                            PeriodicalId = Int32.Parse(item)
                        }.PostAdd();
                    }
                    catch { }
                }
                return article;
            }
            return null;
        }
        public static List<Purpose> GetAllPurpose(int periodicalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Purpose
                            join p in ctx.Periodical
                             on c.PeriodicalId equals p.Id
                            join a in ctx.Article
                             on c.ArticleId equals a.Id
                            where c.PeriodicalId == periodicalId
                            orderby c.Id descending
                            select new { c, p, a })
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Purpose().Set(c.c).LoadPeriodical(c.p).LoadArticle(c.a))
                           .ToList();
                return data;
            }
        }
        public static int GetAllPurposeForPage(int periodicalId)
        {
            using (Context ctx = new Context())
            {
                return ctx.Purpose.Count(c => c.PeriodicalId == periodicalId);
            }
        }
        public static List<Article> GetMyManuscript(string userName, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = ctx.Article.Where(c => c.UserName == userName)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Article().Set(c))
                    .ToList();
                return data;
            }
        }
        public static int GetMyManuscriptForPage(string userName)
        {
            using (Context ctx = new Context())
            {
                return ctx.Article.Count(c => c.UserName == userName);
            }
        }
        public static List<Article> GetMyManuscriptAndLoadMessage(string userName, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Article
                            join m in ctx.MessageBoard
                             on c.Id equals m.RelateId into o
                            from i in o.DefaultIfEmpty()
                            where c.UserName == userName 
                            group new {c,i} by c.Id into g
                            orderby g.Key descending
                            select g)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Article().Set(c.FirstOrDefault().c)
                               .LoadMessages(
                               c.Select(i=>new MessageBoard().Set(i.i))
                               .ToList()))
                           .ToList();
                return data;
                           
            }
        }
        /// <summary>
        /// 获取所代理的期刊的新稿件 status = open
        /// </summary>
        /// <param name="agentUsername"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Article> GetMyAgentPeriodicalManuscript(string agentUsername, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Agent
                            join p in ctx.Purpose
                                on c.PeriodicalId equals p.PeriodicalId
                            join m in ctx.Article
                             on p.ArticleId equals m.Id 
                            join j in ctx.Periodical
                                on c.PeriodicalId equals j.Id
                            where c.UserName == agentUsername && !m.IsDelete
                            orderby m.Id descending
                            select new { m, j })
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Article().Set(c.m).LoadPeriodical(c.j))
                           .ToList();
                return data;

            }
        }

        public static int GetMyAgentPeriodicalManuscriptForPage(string agentUsername)
        {
            using (Context ctx = new Context())
            {
                return ctx.Article.Where(c => c.UserName == agentUsername && !c.IsDelete).Count();
            }
        }
        #endregion

        #region 约稿相关
        /// <summary>
        /// 申请约稿人
        /// </summary>
        /// <param name="id"></param>
        /// <param name="about"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static ApplySheet EditorApply(int periodicalId, string about, string agentUsername)
        {
            var user = new User().Find(agentUsername);
            if (user == null || user.SystemRole != UserRole.PaperAgent)
            {
                return null;
            }
            var periodical = new Periodical().Find(periodicalId.ToString());
            if (periodical == null || new Agent().Any(c => c.UserName == agentUsername && c.PeriodicalId == periodicalId))
            {
                return null;
            }
            var apply = new ApplySheet().Find(c => c.Username == agentUsername && c.PerodicalId == periodicalId);
            if (apply != null && apply.Status == 0)
            {
                apply.ApplyDate = DateTime.Now;
                apply.ApplyContent = about;
                apply.PostModify();
            }
            else if(apply == null || apply.Status == 2)
            {
                apply = new ApplySheet()
                {
                    ApplyContent = about,
                    ApplyDate = DateTime.Now,
                    PerodicalId = periodicalId,
                    Username = agentUsername,
                    Status=0,
                    HandleDate=DateTime.Now
                }.PostAdd();
            }
            if (apply != null)
            {
                string toAgent = EmailBuilder.BuildEditorApply(periodical.Name,agentUsername);
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                               new NormalNotifyEmail()
                               {
                                   Message = toAgent,
                                   Title = SiteResource.SiteName + "-- 约稿人申请已发出",
                                   Recipient = agentUsername
                               });

                string support = System.Configuration.ConfigurationManager.AppSettings["support"];
                if (!String.IsNullOrEmpty(support))
                {
                    string[] email = support.Split(',');
                    foreach (var u in email)
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                Message = EmailBuilder.BuildEditorApplyNotify(periodical.Name, agentUsername),
                                Title = SiteResource.SiteName + "-- 有人申请期刊约稿人",
                                Recipient = u
                            });
                    }
                }
            }
            return apply;
        }
        /// <summary>
        /// 查询所有约稿人申请表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static List<ApplySheet> GetAllEditorApply(int page,int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.ApplySheet
                            join p in ctx.Periodical
                             on c.PerodicalId equals p.Id
                            join u in ctx.User
                             on c.Username equals u.UserName
                            where c.Status == 0
                            orderby c.Id ascending
                            select new { c, p, u })
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new ApplySheet().Set(c.c)
                               .LoadPeriodical(c.p)
                               .LoadUser(c.u))
                           .ToList();
                return list;
            }
        }
        public static int GetAllEditorApplyForPage()
        {
            using (Context ctx = new Context())
            {
                return ctx.ApplySheet.Count(c=>c.Status == 0);
            }
        }
        /// <summary>
        /// 获取期刊的所有约稿人
        /// </summary>
        /// <param name="periodicalId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Agent> GetAllPeriodicalAgent(int periodicalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Agent
                            join u in ctx.User
                               on c.UserName equals u.UserName
                            join i in ctx.PaperAgentInfo
                               on c.UserName equals i.Username
                            where c.PeriodicalId == periodicalId
                            orderby c.Rank descending
                            select new { c, u, i })
                         .Skip(page * pageSize)
                         .Take(pageSize)
                         .ToList()
                         .Select(c => new Agent().Set(c.c).LoadUser(c.u).LoadAgentInfo(c.i))
                         .ToList();
                return data;
            }
        }
        public static int GetAllAgentMessageForPage(int id)
        {
            using (Context ctx = new Context())
            {
                return ctx.MessageBoard.Count(c => c.RelateId == id && c.To == 1 && c.MessageType == 1);
            }
        }
        /// <summary>
        /// 获取针对某一意向的所有约稿留言
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<MessageBoard> GetAllAgentMessage(int articleId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.MessageBoard
                            join a in ctx.Article
                             on c.RelateId equals a.Id
                            join u in ctx.PaperAgentInfo
                             on c.From equals u.Username
                            where c.To == 1 && c.MessageType == 1 && c.RelateId == articleId
                            orderby c.Id descending
                            select new { a, c, u })
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new MessageBoard().Set(c.c)
                               .LoadArticle(c.a)
                               .LoadAgentInfo(c.u))
                           .ToList();
                return data;
            }
        }
        /// <summary>
        /// 发一条约稿留言
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="userName"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static MessageBoard NewMessageForArticle(int articleId, string userName, string message)
        {
            var user = new User().Find(userName);
            if (user != null && user.SystemRole == UserRole.PaperAgent)
            {
                var article = new Article().Find(articleId.ToString());
                var agentInfo = new PaperAgentInfo().Find(userName);
                if (article != null && agentInfo != null)
                {
                    var messageBoard = new MessageBoard()
                    {
                        CreateDate = DateTime.Now,
                        From = userName,
                        FromName = agentInfo.Name,
                        Message = message,
                        MessageType = 1,
                        RelateId = articleId,
                        To = 1
                    };
                    return messageBoard.PostAdd();
                }
            }
            return null;
        }
        /// <summary>
        /// 发起一个新约稿
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="agentUserName"></param>
        /// <param name="price"></param>
        /// <param name="introduction"></param>
        /// <returns></returns>
        public static Trade NewTrading(int articleId,string agentUserName, decimal price, string introduction)
        {
            var article = new Article().Find(articleId.ToString());
            var agentInfo = new PaperAgentInfo().Find(agentUserName);
            if (article == null || agentInfo == null)
            {
                return null;
            }
            var trading = new Trade() 
            { 
                ArticleId=articleId,
                Consumer=article.UserName,
                Description=introduction,
                Momey=price,
                OpenDate=DateTime.Now,
                Status = TradeStatus.Open,
                Supplier=agentInfo.Username,
                Token=AesAlgorithm.Encrypt(Guid.NewGuid().ToString()),
                PeriodicalId = -1,
                OpenUsername=HttpContext.Current.User.Identity.Name,
                IsDelete=false
            }.PostAdd();

            new TradeHistory()
            {
                NxtStatus = TradeStatus.Open,
                PreStatus = TradeStatus.Open,
                Operator = HttpContext.Current.User.Identity.Name,
                RecordDate = DateTime.Now,
                TradeId = trading.Id
            }.PostAdd();

            if (trading != null)
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user != null)
                {
                    if (user.SystemRole == UserRole.Member)
                    {
                        string toAgent = EmailBuilder.BuildNewTradingToAgentEmail(agentInfo.Name);
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                       new NormalNotifyEmail()
                                       {
                                           Message = toAgent,
                                           Title = SiteResource.SiteName + "-- 约稿提示",
                                           Recipient = agentUserName
                                       });
                    }
                    else if (user.SystemRole == UserRole.PaperAgent)
                    {
                        string toMember = EmailBuilder.BuildNewTradingEmail(agentInfo.Name);
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                       new NormalNotifyEmail()
                                       {
                                           Message = toMember,
                                           Title = SiteResource.SiteName + "-- 约稿提示",
                                           Recipient = article.UserName
                                       });
                    }
                }
            }
            return trading;
        }
        /// <summary>
        /// 投稿者主动向约稿人对某个期刊
        /// </summary>
        /// <param name="id"></param>
        /// <param name="p"></param>
        public static Trade PeriodicalLaunch(int periodicalId,string memberName, string agentName,string Phone,string QQ,decimal price,string introduction)
        {
            var periodical = new Periodical().Find(periodicalId.ToString());
            var pAgent = new PaperAgentInfo().Find(agentName);
            if (periodical == null || !periodical.IsActive || pAgent == null || !new Agent().Any(c=>c.UserName == agentName && c.PeriodicalId == periodicalId))
            {
                return null;
            }

            var trade = new Trade()
            {
                ArticleId = -1,
                Consumer = memberName,
                Description = introduction + "<br /> 联系电话：" + Phone + "<br />联系QQ:" + QQ,
                Momey = price,
                OpenDate = DateTime.Now,
                Status = TradeStatus.Open,
                Supplier = pAgent.Username,
                Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString()),
                PeriodicalId=periodical.Id,
                OpenUsername=HttpContext.Current.User.Identity.Name,
                IsDelete=false
            }.PostAdd();

            new TradeHistory()
            {
                NxtStatus = TradeStatus.Open,
                PreStatus = TradeStatus.Open,
                Operator = HttpContext.Current.User.Identity.Name,
                RecordDate = DateTime.Now,
                Remark = "发起约稿",
                TradeId = trade.Id
            }.PostAdd();
            if (trade != null)
            {
                string toAgent = EmailBuilder.BuildNewTradingToAgentEmail(pAgent.Name);
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                               new NormalNotifyEmail()
                               {
                                   Message = toAgent,
                                   Title = SiteResource.SiteName + "-- 投稿人向您发来一份约稿信息",
                                   Recipient = pAgent.Username
                               });
            }
            return trade;
        }
        public static ApplySheet RefuseEditorApply(int id)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user != null && user.SystemRole == UserRole.Admin) 
                {
                    var apply = new ApplySheet().Find(id.ToString());
                    if (apply != null)
                    {
                        apply.Status = 2;
                        apply.HandleDate = DateTime.Now;
                        if (apply.PostModify() != null)
                        {
                            return apply;
                        }
                    }
                }
            }
            return null;
        }
        public static ApplySheet AgreeEditorApply(int id)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user != null && user.SystemRole == UserRole.Admin)
                {
                    var apply = new ApplySheet().Find(id.ToString());
                    if (apply != null)
                    {
                        var agent = new Agent().Find(c => c.UserName == apply.Username && c.PeriodicalId == apply.PerodicalId);
                        if (agent == null)
                        {
                            apply.Status = 1;
                            apply.HandleDate = DateTime.Now;
                            if (apply.PostModify() != null)
                            {
                                if (new Agent()
                                {
                                    PeriodicalId = apply.PerodicalId,
                                    RecordDate = DateTime.Now,
                                    RefreshDate = DateTime.Now,
                                    UserName = apply.Username,
                                    Rank = 1
                                }.PostAdd() != null)
                                {
                                    return apply;
                                }
                            }
                        }
                        else
                        {
                            apply.Status = 2;
                            apply.HandleDate = DateTime.Now;
                            apply.PostModify();
                            return apply;
                        }
                    }
                }
            }
            return null;
        }
        #endregion

        #region 交易相关
        public static int GetMyNewOrderForPage(string userName)
        {
            var user = new User().Find(userName);
            if(user == null)
            {
                return 0;
            }
            using (Context ctx = new Context())
            {
                if (user.SystemRole == UserRole.Member)
                {
                    return ctx.Trade.Count(c =>
                        c.Consumer == userName && c.Status == (int)TradeStatus.Open && !c.IsDelete);
                }
                else
                {
                    return ctx.Trade.Count(c =>
                        c.Supplier == userName && c.Status == (int)TradeStatus.Open && !c.IsDelete);
                }
            }
        }
        /// <summary>
        /// 获取订单
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static List<Trade> GetMyAllOrder(string userName,int page,int pageSize)
        {
            var user = new User().Find(userName);
            if (user == null)
            {
                return null;
            }
            using (Context ctx = new Context())
            {
                if (user.SystemRole == UserRole.Member)
                {
                    var data = (from c in ctx.Trade
                                join oa in ctx.Organization
                                 on c.Organization equals oa.Id into oo
                                from o in oo.DefaultIfEmpty()
                                join pa in ctx.PaperAgentInfo
                                 on c.Supplier equals pa.Username into pao
                                from p in pao.DefaultIfEmpty()
                                join at in ctx.Article
                                 on c.ArticleId equals at.Id into ao
                                from a in ao.DefaultIfEmpty()
                                join pd in ctx.Periodical
                                 on c.PeriodicalId equals pd.Id into po
                                from pa in po.DefaultIfEmpty()
                                where c.Consumer == userName && !c.IsDelete
                                orderby c.Id descending
                                select new { c, p, a, pa ,o})
                               .Skip(page * pageSize)
                               .Take(pageSize)
                               .ToList()
                               .Select(c => new Trade().Set(c.c)
                                   .LoadAgentInfo(c.p)
                                   .LoadArticle(c.a)
                                   .LoadPeriodical(c.pa)
                                   .LoadOranization(c.o))
                               .ToList();
                    return data;
                }
                else
                {
                    var data = (from c in ctx.Trade
                                join oa in ctx.Organization
                                on c.Organization equals oa.Id into oo
                                from o in oo.DefaultIfEmpty()
                                join p in ctx.PaperAgentInfo
                                 on c.Supplier equals p.Username
                                join at in ctx.Article
                                 on c.ArticleId equals at.Id into ao
                                from a in ao.DefaultIfEmpty()
                                join pd in ctx.Periodical
                                 on c.PeriodicalId equals pd.Id into po
                                from pa in po.DefaultIfEmpty()
                                where c.Supplier == userName && !c.IsDelete
                                orderby c.Id descending
                                select new { c, p, a, pa, o })
                               .Skip(page * pageSize)
                               .Take(pageSize)
                               .ToList()
                               .Select(c => new Trade().Set(c.c)
                                   .LoadAgentInfo(c.p)
                                   .LoadArticle(c.a)
                                   .LoadPeriodical(c.pa)
                                   .LoadOranization(c.o))
                               .ToList();
                    return data;
                }
            }
        }
        public static int GetMyAllOrderForPage(string userName)
        {
            var user = new User().Find(userName);
            if (user == null)
            {
                return 0;
            }
            using (Context ctx = new Context())
            {
                if (user.SystemRole == UserRole.Member)
                {
                    return ctx.Trade.Count(c =>
                        c.Consumer == userName && !c.IsDelete);
                }
                else
                {
                    return ctx.Trade.Count(c =>
                        c.Supplier == userName && !c.IsDelete);
                }
            }
        }
        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="OptionType">
        /// 1：接收约稿；2：取消约稿；3：确认已发表
        /// 4：延长时限；5：出现争议；6：支付已确认
        /// 9：删除约稿</param>
        /// <param name="Id"></param>
        /// <returns>-1:操作失败 1:操作成功 100:该操作交易已被取消 200:交易内容发生变动，请重新确认</returns>
        public static int OrderOption(int OptionType, int TradeId,string Token)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                string userName = HttpContext.Current.User.Identity.Name.ToLower();
                var trade = new Trade().Find(TradeId.ToString());
                if (trade.IsDelete)
                {
                    return 100;
                }
                if (trade != null && trade.Token == Token)
                {
                    switch (OptionType)
                    {
                        case 1: //接受
                            #region 接受
                            if (trade.OpenUsername.ToLower() != userName.ToLower() && (trade.Consumer.ToLower() == userName ||
                               trade.Supplier == userName))
                            {
                                var tradeHistory = new TradeHistory() { 
                                    PreStatus= trade.Status,
                                    NxtStatus = TradeStatus.WaitPay,
                                    Operator=HttpContext.Current.User.Identity.Name,
                                    RecordDate=DateTime.Now,
                                    Remark="接收约稿",
                                    TradeId = trade.Id
                                };
                                trade.Status = TradeStatus.WaitPay;
                                trade.LastModify = DateTime.Now;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());
                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }
                                if (HttpContext.Current.User.Identity.Name == trade.Supplier)
                                {
                                    string toMember = EmailBuilder.BuildAcceptTradeForMember(trade.Consumer);
                                    if (!String.IsNullOrEmpty(toMember))
                                    {
                                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                       new NormalNotifyEmail()
                                                       {
                                                           Message = toMember,
                                                           Title = "您的约稿已被接受 -- " + SiteResource.SiteName,
                                                           Recipient = trade.Consumer
                                                       });
                                    }
                                }
                                if (HttpContext.Current.User.Identity.Name == trade.Consumer)
                                {
                                    string toAgent = EmailBuilder.BuildAcceptTradeForAgent(trade.Supplier);
                                    if (!String.IsNullOrEmpty(toAgent))
                                    {
                                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                       new NormalNotifyEmail()
                                                       {
                                                           Message = toAgent,
                                                           Title = "您有一份约稿已被接受 -- " + SiteResource.SiteName,
                                                           Recipient = trade.Supplier
                                                       });
                                    }
                                }
                            }
                            #endregion
                            return 1;
                        case 2: //拒绝
                            #region 拒绝
                            if (trade.Consumer.ToLower() == userName ||
                               trade.Supplier.ToLower() == userName)
                            {
                                var tradeHistory = new TradeHistory()
                                {
                                    PreStatus = trade.Status,
                                    NxtStatus = TradeStatus.Cancel,
                                    Operator = HttpContext.Current.User.Identity.Name,
                                    RecordDate = DateTime.Now,
                                    Remark = "拒绝约稿",
                                    TradeId = trade.Id
                                };

                                trade.Status = TradeStatus.Cancel;
                                trade.LastModify = DateTime.Now;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }  
                            }
                            #endregion
                            return 1;
                        case 3: //确认已发表
                            #region 确认已发表
                            if (trade.Consumer.ToLower() == userName) //如果是投稿人确认的已经发表
                            {
                                if (trade.Status == TradeStatus.Execute)
                                {
                                    new TradeHistory()
                                    {
                                        PreStatus = trade.Status,
                                        NxtStatus = TradeStatus.TradeConfirm_m,
                                        Operator = HttpContext.Current.User.Identity.Name,
                                        RecordDate = DateTime.Now,
                                        Remark = "投稿人确认已发表",
                                        TradeId = trade.Id
                                    }.PostAdd();
                                    trade.Status = TradeStatus.TradeConfirm_m;
                                }
                                var tradeHistory = new TradeHistory()
                                {
                                    PreStatus = trade.Status,
                                    NxtStatus = TradeStatus.TradeIsConfirm,
                                    Operator = HttpContext.Current.User.Identity.Name,
                                    RecordDate = DateTime.Now,
                                    Remark = "投稿人确认稿件已发表",
                                    TradeId = trade.Id
                                };

                                trade.ConfirmExpireDate = DateTime.Now;
                                trade.ConfirmTradeDate = DateTime.Now;
                                trade.LastModify = DateTime.Now;
                                trade.Status = TradeStatus.TradeIsConfirm;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }  
                            }
                            else if (trade.Supplier.ToLower() == userName)
                            {
                                var tradeHistory = new TradeHistory()
                                {
                                    PreStatus = trade.Status,
                                    NxtStatus = TradeStatus.TradeConfirm_o,
                                    Operator = HttpContext.Current.User.Identity.Name,
                                    RecordDate = DateTime.Now,
                                    Remark = "约稿人确认稿件已发表，等待投稿人确认",
                                    TradeId = trade.Id
                                };

                                trade.ConfirmExpireDate = DateTime.Parse(DateTime.Now.AddDays(7).ToString("yyyy-MM-dd 23:59:59"));
                                trade.ConfirmTradeDate = DateTime.Now;
                                trade.LastModify = DateTime.Now;
                                trade.Status = TradeStatus.TradeConfirm_o;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                                string toAgent = EmailBuilder.BuildPublishConfirmNotice(trade);
                                if (!String.IsNullOrEmpty(toAgent))
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                   new NormalNotifyEmail()
                                                   {
                                                       Message = toAgent,
                                                       Title = "约稿人确认了您的稿件已经发表，请尽快检查确认 -- " + SiteResource.SiteName,
                                                       Recipient = trade.Consumer
                                                   });
                                }

                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }  
                            }
                            #endregion
                            return 1;
                        case 4: //延长时限
                            #region 延长时限
                            if (trade.Consumer.ToLower() == userName)
                            {
                                var tradeHistory = new TradeHistory()
                                {
                                    PreStatus = trade.Status,
                                    NxtStatus = trade.Status,
                                    Operator = HttpContext.Current.User.Identity.Name,
                                    RecordDate = DateTime.Now,
                                    Remark = "延长时限",
                                    TradeId = trade.Id
                                };
                                trade.ConfirmExpireDate = DateTime.Parse(DateTime.Now.AddDays(7).ToString("yyyy-MM-dd 23:59:59"));
                                trade.LastModify = DateTime.Now;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }

                                string toAgent = EmailBuilder.BuildPublishIsdeferredNotice(trade);
                                if (!String.IsNullOrEmpty(toAgent))
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                   new NormalNotifyEmail()
                                                   {
                                                       Message = toAgent,
                                                       Title = "您有一份约稿被投稿人进行了延时处理，请尽快检查确认 -- " + SiteResource.SiteName,
                                                       Recipient = trade.Supplier
                                                   });
                                }
                            }
                            #endregion
                            return 1;
                        case 5: //出现争议
                            #region 出现争议
                            if (trade.Consumer.ToLower() == userName)
                            {
                                var tradeHistory = new TradeHistory()
                                {
                                    PreStatus = trade.Status,
                                    NxtStatus = TradeStatus.Dispute,
                                    Operator = HttpContext.Current.User.Identity.Name,
                                    RecordDate = DateTime.Now,
                                    Remark = "出现争议",
                                    TradeId = trade.Id
                                };
                                trade.Status = TradeStatus.Dispute;
                                trade.LastModify = DateTime.Now;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }

                                string toAgent = EmailBuilder.BuildPublishIsDisputeNotice(trade);
                                if (!String.IsNullOrEmpty(toAgent))
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                   new NormalNotifyEmail()
                                                   {
                                                       Message = toAgent,
                                                       Title = "您有一份约稿被投稿人进行了争议处理，请尽快检查确认 -- " + SiteResource.SiteName,
                                                       Recipient = trade.Supplier
                                                   });
                                }
                            }
                            #endregion
                            return 1;
                        case 6: //支付已确认
                            #region 支付已确认
                            if (trade.Token == Token && trade.Status == TradeStatus.Pay)
                            {
                                var tradeHistory = new TradeHistory()
                                {
                                    PreStatus = trade.Status,
                                    NxtStatus = TradeStatus.Execute,
                                    Operator = HttpContext.Current.User.Identity.Name,
                                    RecordDate = DateTime.Now,
                                    Remark = "支付确认完成",
                                    TradeId = trade.Id
                                };
                                trade.Status = TradeStatus.Execute;
                                trade.LastModify = DateTime.Now;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }

                                string toMember = EmailBuilder.BuildPayConfirmNotice(trade);
                                if (!String.IsNullOrEmpty(toMember))
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                   new NormalNotifyEmail()
                                                   {
                                                       Message = toMember,
                                                       Title = "约稿人已完成支付确认 -- " + SiteResource.SiteName,
                                                       Recipient = trade.Consumer
                                                   });
                                }
                            }
                            #endregion
                            return 1;
                        case 9://删除订单
                            #region 删除订单
                            if (trade.Consumer.ToLower() == userName ||
                                trade.Supplier.ToLower() == userName)
                            {
                                var tradeHistory = new TradeHistory()
                                {
                                    PreStatus = trade.Status,
                                    NxtStatus = trade.Status,
                                    Operator = HttpContext.Current.User.Identity.Name,
                                    RecordDate = DateTime.Now,
                                    Remark = "删除约稿信息",
                                    TradeId = trade.Id
                                };

                                trade.IsDelete = true;
                                trade.LastModify = DateTime.Now;
                                trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());
                                
                                if (trade.PostModify() != null)
                                {
                                    tradeHistory.PostAdd();
                                }  
                            }
                            #endregion
                            return 1;

                    }
                }
                return 200;
            }
            return -1;
        }
        #endregion

        #region 行业投稿相关
        public static List<Trade> GetIndustryOrders(string userName, int page, int pageSize)
        {
            var user = new User().Find(userName);
            if (user == null || user.Industry == 0 || 
                !new IndustryCS().Any(c=>c.UserName == userName && c.Organization == user.Industry))
            {
                return null;
            }
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Trade
                            join u in ctx.User
                                on c.Consumer equals u.UserName
                            join spu in ctx.User
                                 on c.Supplier equals spu.UserName into su
                            from s in su.DefaultIfEmpty()
                            where c.Organization == user.Industry && !c.IsDelete
                            orderby c.Id descending
                            select new { c, Consumer = u.NickName, Supplier = s == null ? "" : s.NickName })
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c =>
                           {
                               var trade = new Trade().Set(c.c);
                               trade.ConsumerName = c.Consumer;
                               trade.SupplierName = c.Supplier;
                               return trade;
                           })
                           .ToList();
                return data;

            }
        }
        public static int GetIndustryOrderForPage(string userName)
        {
            var user = new User().Find(userName);
            if (user == null || user.Industry == 0 ||
                !new IndustryCS().Any(c => c.UserName == userName && c.Organization == user.Industry))
            {
                return 0;
            }
            using (Context ctx = new Context())
            {
                return ctx.Trade.Count(c =>
                     c.Organization == user.Industry && !c.IsDelete);
            }
        }
        /// <summary>
        /// 获取所有行业投稿承办机构
        /// </summary>
        /// <returns></returns>
        public static List<Organization> GetIndustryOrganization()
        {
            using (Context ctx = new Context())
            {
                var data = ctx.Organization.ToList()
                    .Select(c => new Organization().Set(c))
                    .ToList();
                return data;
            }
        }
        /// <summary>
        /// 获取行业投稿客服
        /// </summary>
        /// <param name="org">机构名称</param>
        /// <param name="page"></param>
        /// <returns></returns>
        public static List<IndustryCS> GetIndustryCS(int org, bool exceptDisable, int page,int pageSize)
        {
            using (Context ctx = new Context())
            {
                var query = from c in ctx.IndustryCS
                            join o in ctx.Organization
                                on c.Organization equals o.Id
                            join u in ctx.User
                                on c.UserName equals u.UserName
                            select new { c, u, o.Organization };
                if (org > 0)
                {
                    query = query.Where(c => c.c.Organization == org);
                }
                if (exceptDisable)
                {
                    query = query.Where(c => c.c.Enable);
                }
                return query.OrderByDescending(c => c.c.CreateTime)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new IndustryCS().Set(c.c)
                        .LoadUser(c.u)
                        .SetOrganiztionName(c.Organization))
                    .ToList();
            }
        }
        public static int GetIndustryCSCount(int org,bool exceptDisable)
        {
            using (Context ctx = new Context())
            {
                var query = ctx.IndustryCS.Where(c => c.Enable);
                if (org>0)
                {
                    query = query.Where(c => c.Organization == org);
                }
                if (exceptDisable)
                {
                    query = query.Where(c => c.Enable);
                }
                return query.Count();
            }
        }
        public static IndustryCS newIndustryCS(IndustryCS cs)
        {
            if (cs != null)
            {
                if (new User().Any(c=>c.UserName == cs.UserName))
                {
                    cs.PostAdd();
                }
            }
            return cs;
        }
        /// <summary>
        /// 修改客户状态
        /// </summary>
        /// <param name="option">0：禁用 1：启用 9：删除</param>
        /// <param name="username"></param>
        public static void CsOption(int option, string username)
        {
            var user = new User().Find(username);
            if (user != null && user.SystemRole == UserRole.PaperAgent)
            {
                var cs = new IndustryCS().Find(username);
                if (cs != null)
                {
                    if (option == 0)
                    {
                        cs.Enable = false;
                        user.IsRefuse = true;
                        cs.PostModify();
                        user.PostModify();
                    }
                    else if (option == 1)
                    {
                        cs.Enable = true;
                        user.IsRefuse = false;
                        cs.PostModify();
                        user.PostModify();
                    }
                    else if (option == 9)
                    {
                        var agent = new PaperAgentInfo().Find(username);
                        if (agent != null)
                        {
                            agent.PostDelete();
                        }
                        user.PostDelete();
                        cs.PostDelete();
                    }
                }
            }
        }
        public static Trade IndustryLaunch(int organizationId, string consumer, string phone,
            string QQ, string introduction)
        {
            var organization = new Organization().Find(organizationId.ToString());
            var user = new User().Find(consumer);
            if (organization != null && user != null && user.IsActivate && !user.IsRefuse)
            {
                var trade = new Trade()
                {
                    ArticleId = -1,
                    Consumer = consumer,
                    Description = introduction + "<br />联系电话：" + phone + "<br />联系QQ：" + QQ,
                    IsDelete = false,
                    LastModify = DateTime.Now,
                    OpenDate = DateTime.Now,
                    OpenUsername = consumer,
                    Organization = organization.Id,
                    Status = TradeStatus.Open,
                    Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString()),
                    PeriodicalId = -1
                }.PostAdd();

                if (trade != null)
                {
                    new TradeHistory()
                    {
                        NxtStatus = TradeStatus.Open,
                        Operator = HttpContext.Current.User.Identity.Name,
                        PreStatus = TradeStatus.Open,
                        RecordDate = DateTime.Now,
                        Remark = "发起行业约稿",
                        TradeId = trade.Id
                    }.PostAdd();
                    return trade;
                }
                return null;
            }
            return null;
        }
        public static int IndustryOrderOption(int OptionType, decimal price, int TradeId, string Token)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                string userName = HttpContext.Current.User.Identity.Name.ToLower();
                var trade = new Trade().Find(TradeId.ToString());
                var industryCS = new IndustryCS().Find(HttpContext.Current.User.Identity.Name);
                if (trade.IsDelete)
                {
                    return 100;
                }
                if (trade != null && industryCS.Enable &&
                    industryCS.Organization == trade.Organization && trade.Token == Token)
                {
                    TradeHistory tradeHistory = null;
                    switch (OptionType)
                    {
                        case 1: //接受
                            #region 接受
                            tradeHistory = new TradeHistory()
                            {
                                PreStatus = trade.Status,
                                NxtStatus = TradeStatus.WaitPay,
                                Operator = HttpContext.Current.User.Identity.Name,
                                RecordDate = DateTime.Now,
                                Remark = "接收行业约稿",
                                TradeId = trade.Id
                            };
                            trade.Supplier = HttpContext.Current.User.Identity.Name;
                            trade.Status = TradeStatus.WaitPay;
                            trade.LastModify = DateTime.Now;
                            trade.Momey = price;
                            trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());
                            if (trade.PostModify() != null)
                            {
                                tradeHistory.PostAdd();
                            }

                            if (HttpContext.Current.User.Identity.Name == trade.Supplier)
                            {
                                string toMember = EmailBuilder.BuildAcceptTradeForMember(trade.Consumer);
                                if (!String.IsNullOrEmpty(toMember))
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                   new NormalNotifyEmail()
                                                   {
                                                       Message = toMember,
                                                       Title = "您的约稿已被接受 -- " + SiteResource.SiteName,
                                                       Recipient = trade.Consumer
                                                   });
                                }
                            }
                            if (HttpContext.Current.User.Identity.Name == trade.Consumer)
                            {
                                string toAgent = EmailBuilder.BuildAcceptTradeForAgent(trade.Supplier);
                                if (!String.IsNullOrEmpty(toAgent))
                                {
                                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                   new NormalNotifyEmail()
                                                   {
                                                       Message = toAgent,
                                                       Title = "您有一份约稿已被接受 -- " + SiteResource.SiteName,
                                                       Recipient = trade.Supplier
                                                   });
                                }
                            }
                            #endregion
                            return 1;
                        case 2: //拒绝
                            #region 拒绝
                            tradeHistory = new TradeHistory()
                            {
                                PreStatus = trade.Status,
                                NxtStatus = TradeStatus.Cancel,
                                Operator = HttpContext.Current.User.Identity.Name,
                                RecordDate = DateTime.Now,
                                Remark = "拒绝约稿",
                                TradeId = trade.Id
                            };

                            trade.Status = TradeStatus.Cancel;
                            trade.LastModify = DateTime.Now;
                            trade.Supplier = HttpContext.Current.User.Identity.Name;
                            trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                            if (trade.PostModify() != null)
                            {
                                tradeHistory.PostAdd();
                            }

                            #endregion
                            return 1;
                        case 9://删除订单
                            #region 删除订单
                            tradeHistory = new TradeHistory()
                            {
                                PreStatus = trade.Status,
                                NxtStatus = trade.Status,
                                Operator = HttpContext.Current.User.Identity.Name,
                                RecordDate = DateTime.Now,
                                Remark = "删除约稿信息",
                                TradeId = trade.Id
                            };

                            trade.Supplier = HttpContext.Current.User.Identity.Name;
                            trade.IsDelete = true;
                            trade.LastModify = DateTime.Now;
                            trade.Token = AesAlgorithm.Encrypt(Guid.NewGuid().ToString());

                            if (trade.PostModify() != null)
                            {
                                tradeHistory.PostAdd();
                            }

                            #endregion
                            return 1;

                    }
                }
                return 200;
            }
            return -1;
        }
        #endregion
    }
}
